import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { Modal, Row, Col, Switch, Icon, Spin, Tooltip, Popover, Tag } from 'antd'
import financeAuditService from 'containers/financial-management/finance-audit/finance-audit.service'
import 'styles/financial-management/finance-audit/file-audit.scss'
import FileViewer from "components/file-viewer";

class FileAudit extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      invoices: [],
      nowInvoiceIndex: 0,
      nowAttachmentIndex: 0,
      totalAttachments: 0,
      checking: false,
      change: false
    };
  }

  componentDidMount(){
    if (window.addEventListener) {
      window.addEventListener('keyup', this.handleKeyUp);
    } else {
      window.attachEvent('onkeyup', this.handleKeyUp);
    }
  }

  componentWillReceiveProps(nextProps){
    const { invoices, visible, defaultImage } = nextProps;
    //显示时初始化
    if(visible && !this.props.visible){
      let result = [];
      let totalAttachments = 0;
      let nowInvoiceIndex = 0, nowAttachmentIndex = 0;
      console.log('invoices', invoices)
      invoices.map(invoice => {
        let allChecked = true;
        let target = invoice;
        let attachments = [];
        invoice.receiptList.map(invoice => {
          let attachment = invoice.slicingAttachment || invoice.originAttachment;
          attachment && (attachments.push(attachment));
        });
        target.attachments = attachments.concat(target.attachments);
        if(target.attachments && target.attachments.length > 0){
          target.attachments.map(attachment => {
            allChecked = allChecked && attachment.checked;
          });
          target.allChecked = allChecked;
          result.push(target);
          totalAttachments += target.attachments.length;
        }
        invoice.isExpand = false;
      });
      result.map((invoice, invoiceIndex) => {
        invoice.attachments.map((attachment, attachmentIndex) => {
          if(defaultImage && defaultImage.attachmentOID === attachment.attachmentOID){
            nowInvoiceIndex = invoiceIndex;
            nowAttachmentIndex = attachmentIndex;
          }
        });
      });
      this.setState({ invoices: result, totalAttachments, nowInvoiceIndex, nowAttachmentIndex});
    }
  }

  componentWillUnmount(){
    if (window.addEventListener) {
      window.removeEventListener('keyup', this.handleKeyUp);
    } else {
      window.detachEvent('onkeyup', this.handleKeyUp);
    }
  }

  //键盘事件
  handleKeyUp = (e) => {
    e.stopPropagation();
    let { nowAttachmentIndex, nowInvoiceIndex, invoices } = this.state;
    const { visible, isEnableCheck } = this.props;
    if(visible){
      switch(e.keyCode){
        //空格
        case 32: {
          if (isEnableCheck) {
            this.handleCheckAttachment(!invoices[nowInvoiceIndex].attachments[nowAttachmentIndex].checked  ,nowInvoiceIndex, nowAttachmentIndex)
          }
          break;
        }
        //⬅
        case 37: {
          if(nowAttachmentIndex !== 0)
            this.handleSelectAttachment(--nowAttachmentIndex);
          break;
        }
        //⬆
        case 38:{
          if(nowInvoiceIndex !== 0)
            this.handleSelectInvoice(--nowInvoiceIndex);
          break;
        }
        //➡
        case 39:{
          if(nowAttachmentIndex !== invoices[nowInvoiceIndex].attachments.length - 1)
            this.handleSelectAttachment(++nowAttachmentIndex);
          break;
        }
        //⬇
        case 40:{
          if(nowInvoiceIndex !== invoices.length - 1)
            this.handleSelectInvoice(++nowInvoiceIndex);
          break;
        }
      }
    }
  };

  //审核图片
  handleCheckAttachment = (checked, invoiceIndex, attachmentIndex) => {
    let { invoices, nowInvoiceIndex } = this.state;
    this.setState({ checking: true });
    financeAuditService.checkAttachment({
      attachmentOID: invoices[invoiceIndex].attachments[attachmentIndex].attachmentOID,
      checked,
      invoiceOID: invoices[invoiceIndex].invoiceOID,
    }).then(res => {
      invoices[invoiceIndex].attachments[attachmentIndex].checked = checked;
      let allChecked = true;
      invoices[invoiceIndex].attachments.map(attachment => {
        allChecked = allChecked && attachment.checked;
      });
      invoices[invoiceIndex].allChecked = allChecked;
      this.setState({ invoices, checking: false, nowInvoiceIndex, change: true });
      this.props.onAuditChange(invoices)
    });
  };

  handleSelectAttachment = (index) => {
    this.setState({ nowAttachmentIndex: index });
  };

  handleSelectInvoice = (index) => {
    const {invoices} = this.state;
    invoices.map((item,i) => {
      invoices[i].isExpand = (i === index ? !item.isExpand : false);
    });
    this.setState({ nowInvoiceIndex: index, nowAttachmentIndex: 0, invoices });
  };

  render() {
    const { invoices, nowInvoiceIndex, nowAttachmentIndex, totalAttachments, checking } = this.state;
    const { visible, onCancel, isEnableCheck } = this.props;
    let nowInvoice = invoices[nowInvoiceIndex];
    let attachments = nowInvoice ? nowInvoice.attachments : [];
    let attachment = attachments.length > 0 ? attachments[nowAttachmentIndex] : {};
    const infoContent = (
      <div>
        {`1. ${messages('financial-management.key807')/*此模式下只显示该单据下所有含有发票原件/发票图片/附件的费用*/}；`}<br/>
        {`2. ${messages('financial-management.key808')/*此模式下仅可查看jpg/png/pdf/excel/word/ppt/txt文件*/}；`}<br/>
        {`3. ${messages('financial-management.key809')/*键盘↔️可切换图片/文件，↕️切换费用*/}${isEnableCheck ? `，${messages('financial-management.key838')/*按【空格】标记已核对/未核对*/}；` : '；'}`}<br/>
        {`4. ${messages('financial-management.key810')/*此模式可通过发票图片/发票原件/附件缩略图点击进入*/}；`}<br/>
        {`5. ${messages('financial-management.key839')/*基于各个浏览器兼容性，部分格式文件点击下载按钮，将打开新浏览页，请在新页面右击另存为*/}`}
      </div>
    );
    let allCheckedNumber = invoices.filter(invoice => !!invoice.allChecked).length;
    let modalParams = {
      mask: false,
      getContainer: () => document.querySelector("#invoice-preview"),
      wrapClassName: 'invoice-wrapped-box',
      width: '100%',
      closable: false,
      keyboard: false
    };
    return (
      <Modal
        className="file-audit"
        visible={visible}
        footer={null}
        onCancel={() => onCancel()}
        width='100%'
        destroyOnClose
        title={
          <span className='file-audit-title'>
            {isEnableCheck ? messages('financial-management.key811')/*发票及附件审核*/ : messages('financial-management.key812')/*发票及附件查看*/}
            {messages('common.total', {total: totalAttachments})/*共{totalAttachments}张*/}
            <Tooltip title={infoContent} placement="bottomLeft">
               <Icon type="info-circle" />
            </Tooltip>
          </span>
        }
      >
        <Row className='file-audit-content'>
          <Col span={8} className="invoice-list">
            {isEnableCheck && (
              <div className="invoice-count">
                {messages('financial-management.key210'/*待核对费用*/)}
                <span>{invoices.length - allCheckedNumber}</span>
                {messages('financial-management.key211'/*笔*/)}
              </div>
            )}
            <div className="invoice-container" style={{height: `calc(100vh - ${isEnableCheck ? 105 : 55}px)`}}>
              {invoices.map((invoice, index) => (
                <div style={{overflowX: 'hidden'}} key={index}>
                  <Row className={`invoice-item ${nowInvoiceIndex === index && 'selected-invoice'}`} onClick={() => this.handleSelectInvoice(index)}>
                    {(invoice.allChecked && isEnableCheck) && <Icon type="check-circle" className="selected-icon"/>}
                    {(invoice.receiptList || invoice.summaryInfo) && <Icon type={invoice.isExpand ? 'minus' : 'plus'} className="expand-icon"/>}
                    <Col span={8}><Popover content={new Date(invoice.createdDate).format('yyyy-MM-dd')}>{new Date(invoice.createdDate).format('yyyy-MM-dd')}</Popover></Col>
                    <Col span={8}><Popover content={invoice.expenseTypeName}>{invoice.expenseTypeName}</Popover></Col>
                    <Col span={4}>{invoice.invoiceCurrencyCode}</Col>
                    <Col span={4}><Popover content={this.filterMoney(invoice.amount,queryCurrencyPrecision(invoice.invoiceCurrencyCode))}>{this.filterMoney(invoice.amount,queryCurrencyPrecision(invoice.invoiceCurrencyCode))}</Popover></Col>
                  </Row>
                  <div className='invoice-item' style={{paddingRight: '0px'}}>
                    {invoice.isExpand && (
                      <div className='invoice-expand'>
                        {
                          invoice.summaryInfo && (
                            <Row>
                              <Col span={3}>{messages('financial-management.key610')/*摘要*/}:</Col>
                              <Col span={21}>{invoice.summaryInfo}</Col>
                            </Row>
                          )
                        }
                        {
                          invoice.invoiceLabels && (
                            <Row>
                              {invoice.invoiceLabels.map(item => {
                                let result = '';
                                if (item.level === 'WARN') {
                                  result = <Tag color="red" style={{marginTop: '3px'}}>{item.name}</Tag>;
                                }
                                if (item.level === 'ERROR') {
                                  result = <Tag color="blue" style={{marginTop: '3px'}}>{item.name}</Tag>;
                                }
                                return result;
                              })}
                            </Row>
                          )
                        }
                        {
                          invoice.receiptList && invoice.receiptList.map((item, index) => {
                            return (
                              <div key={index}>
                                <Row>
                                  <Col span={4}>{messages('common.invoice.type')/*发票类型*/}:</Col>
                                  <Col span={20}>{item.type}</Col>
                                </Row>
                                <Row>
                                  <Col span={4}>{messages('financial-management.key611')/*发票代码*/}:</Col>
                                  <Col span={8} style={{paddingRight: '3px'}}>{item.billingCode}</Col>
                                  <Col span={4}>{messages('financial-management.key612')/*发票号码*/}:</Col>
                                  <Col span={8}>{item.billingNo}</Col>
                                </Row>
                                <Row>
                                  <Col span={4}>{messages('financial-management.key613')/*开票日期*/}:</Col>
                                  <Col span={20}>{item.billingTime ? new Date(item.billingTime * 1000).format('yyyy-MM-dd') : ''}</Col>
                                </Row>
                                <Row>
                                  <Col span={4}>{messages('financial-management.key614')/*金额合计*/}:</Col>
                                  <Col span={8} style={{paddingRight: '3px'}}>{typeof item.feeWithoutTax === 'number' ? (item.feeWithoutTax / 100).toFixed(queryCurrencyPrecision()) : '-'}</Col>
                                  <Col span={4}>{messages('financial-management.key615')/*税额合计*/}:</Col>
                                  <Col span={8}>{typeof item.tax === 'number' ? ((item.tax) / 100).toFixed(queryCurrencyPrecision()) : '-'}</Col>
                                </Row>
                                <Row>
                                  <Col span={4}>{messages('financial-management.key616')/*价税合计*/}:</Col>
                                  <Col span={20}>{typeof item.fee === 'number' ? ((item.fee) / 100).toFixed(queryCurrencyPrecision()) : '-'}</Col>
                                </Row>
                              </div>
                            )
                          })
                        }
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </Col>
          <Col span={16} className='invoice-preview'>
            {nowInvoice &&
              (<div>
                <div className="invoice-title">
                  <div className="attachment-status">
                    {checking ? (
                      <div>
                        <Spin/>
                        <span className="attachment-status-description">{messages('financial-management.key212'/*处理中*/)}</span>
                      </div>
                    ) : isEnableCheck && (
                      <div>
                        <Switch
                          size="small"
                          checked={attachment.checked}
                          onChange={checked => this.handleCheckAttachment(checked, nowInvoiceIndex, nowAttachmentIndex)}
                        />
                        <span className="attachment-status-description">
                          {attachment.checked ? messages('financial-management.key213'/*已核对*/) : messages('financial-management.key214'/*未核对*/)}
                        </span>
                      </div>)
                    }
                  </div>
                  {nowInvoice.expenseTypeName}&nbsp;&nbsp;
                  {nowInvoice.invoiceCurrencyCode}{nowInvoice.amount.toFixed(queryCurrencyPrecision(nowInvoice.invoiceCurrencyCode))}
                </div>
                <div id='invoice-preview'>
                  <FileViewer
                    visible={true}
                    markable={isEnableCheck}
                    modalParams={modalParams}
                    attachments={attachments}
                    defaultIndex={nowAttachmentIndex}
                    onClick={this.handleSelectAttachment}
                    urlKey="fileURL"
                    valueKey="id"
                    markKey='checked'
                  />
                  </div>
                </div>
              )}
          </Col>
        </Row>
      </Modal>
    )
  }
}

FileAudit.propTypes = {
  visible: React.PropTypes.bool.isRequired,
  invoices: React.PropTypes.array.isRequired,
  afterClose: React.PropTypes.func,
  onCancel: React.PropTypes.func,
  defaultImage: React.PropTypes.any,
  isEnableCheck: React.PropTypes.bool, //是否启用核对功能
  onAuditChange: React.PropTypes.func, //图片审核后的回调
};

FileAudit.defaultProps = {
  visible: false,
  defaultImage: null,
  isEnableCheck: false,
};

export default FileAudit
